package com.leyou.auth.interceptors;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author GL160601@163.com
 * @date 2020/12/19 11:31
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    //不让他自动生成bean,需要的地方再生成,所以不用@Autowirted
    //构造器注入
    private final JwtUtils jwtUtils;

    public LoginInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        try {
            //获取cookie中的jwt
            String token = CookieUtils.getCookieValue(request, "LY_TOKEN");

            //验证并解析
            Payload payload = jwtUtils.parseJwt(token);
            //获取用户
            UserDetail userDetail = payload.getUserDetail();
            UserContext.setUser(userDetail);
            log.info("用户{}正在访问", userDetail.getUsername());
            return true;
        } catch (JwtException e) {
            throw new LyException(401, "JWT无效或过期!", e);
        } catch (IllegalArgumentException e) {
            throw new LyException(401, "用户未登录！");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //在青丘结束时,清理线程中的用户信息
        UserContext.removeUser();
    }
}
